package com.novel.framework.listener;

import com.novel.framework.config.ProjectConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * 程序启动监听器
 *
 * @author novel
 * @date 2019/12/11
 */
@Component
@Slf4j
public class AppStartListener {
    private final RedisTemplate<Object, Object> redisTemplate;
    private final ProjectConfig projectConfig;

    public AppStartListener(RedisTemplate<Object, Object> redisTemplate, ProjectConfig projectConfig) {
        this.redisTemplate = redisTemplate;
        this.projectConfig = projectConfig;
    }


    @EventListener
    @Async
    public void onApplicationEvent(ApplicationReadyEvent event) {
//        FastJson2JsonRedisSerializer<Object> serializer = new FastJson2JsonRedisSerializer<>(Object.class);
//        redisTemplate.setValueSerializer(serializer);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.afterPropertiesSet();

        printJVMMemoryStat();
        printProjectInfo();
    }

    /**
     * 打印项目基本信息
     */
    private void printProjectInfo() {
        log.info("project info:{}", projectConfig.getProjectInfo());
    }

    /**
     * 打印内存信息
     */
    private void printJVMMemoryStat() {
        Runtime runtime = Runtime.getRuntime();
        float maxMemory = runtime.maxMemory() / (1024 * 1024);
        float usedMemory = (runtime.totalMemory() - runtime.freeMemory()) / 1024 / 1024;
        log.info(String.format("JVM memory (used/max): %.2fMB / %.2fMB", usedMemory, maxMemory));
    }
}
